/**
 * SingleUpload module
 */

  var React = require("react");
  var tool = require("../tool");
  var consts = require("../consts");
  var SingleUpload = React.createClass({
      getInitialState: function (){
          return {
              uploaded: false,
              uploading: false,
              uploadPercent: 0,
              fileName: "",
              infoHtml: "",
              status: ''
          }
      },
      getInitialProps: function (){
          return {
              settings: {},
              parent: {},
              type: ""
          }
      },
      componentWillMount: function (){
          var settings = this.props.settings;

          this.xhr = null;
          this.form = {
              model: {}
          };

          this.url = settings.upload_url;
          this.accept = settings.accept;
          this.size = settings.size || 0;
//          this.is_ios_3d = settings.isIos;
//          this.is_and_3d = settings.isAndroid;
          this.is_zip_3d = settings.isZip;
          this.isUnity3 = settings.isUnity3;
          this.is_audio = settings.isAudio;
          this.is_video = settings.isVideo;
          this.replaceType = this.is_video ? $._("Video") :
              (this.is_audio ? $._("Music") :
                  (this.is_zip_3d ? "" :
                      (this.isUnity3 ? $._("3D Model") : "")));
          this.not_need_narrow = settings.not_need_narrow;
          this.needInfo = settings.needInfo;
          this.upload_info = settings.upload_info || "";
          this.options = {
              beforeSend: this.beforeSend,
              uploadProgress: this.uploadProgress,
              success: this.uploadSuccess,
              error: this.uploadError
          }
      },
      componentDidMount: function (){
          this.initElements();
      },
      initElements: function (){
          this.elements = {
              uploadGroup: $(this.refs.uploadGroup),
              uploadForm: $(this.refs.uploadForm),
              uploadInput: $(this.refs.uploadInput)
          };
      },
      beforeSend: function (xhr, o){
          this.xhr = xhr;
      },
      uploadProgress: function (e, position, total, percent){
          this.setState({
              uploadPercent: percent
          });
      },
      uploadSuccess: function (a){
          var settings = this.props.settings;
          try {
              a = $.evalJSON(a);
          } catch (e) {}

          if (a.status == 'error'){
              this.setState({
                  uploaded: true,
                  uploading: false
              });
              if (typeof settings.error === "function"){
                  settings.error();
              }
          } else {
              var html = a.file_name, md5 = a.md5, url = a.image_src;
              var video_thumbnail = a.video_thumbnail;
              var fbx_js_url = a.fbx_js_url;
              var data;

              if (typeof settings.success === "function"){
                  settings.success();
              }
              if (settings.isIos){
                  data = {
                      md5_ios: md5,
                      url_ios: url,
                      html_ios: html
                  };
              } else if(settings.isAndroid) {
                  data = {
                      md5_android: md5,
                      url_and: url,
                      html_and: html
                  };
              } else if(settings.isAlphaVideo){
                  data = {
                      alpha_md5: md5
                  }
              } else {
                  data = {
                      md5: md5,
                      url: url,
                      html: html
                  };
                  if (video_thumbnail){
                      data["video_thumbnail"] = video_thumbnail;
                  }
                  if (fbx_js_url){
                      data["fbx_js_url"] = fbx_js_url;
                  }
              }
              this.form.model = data;

              this.setState({
                  uploaded: true,
                  uploading: false,
                  infoHtml: html,
                  status: 'success',
              });

              var parent = this.props.parent;
              parent.updateUploaded(true);
              if (settings.isUnity3){
                  parent.setState({
                      unityUploaded: true
                  });
              }
              if (settings.isAlphaVideo || settings.isRgbVideo){
                  if (parent.checkIosAndReady()){
                      parent.setState({
                          videoUploaded: true
                      });
                  }
              }
          }
      },
      uploadError: function (a, b){
          var settings = this.props.settings;
          if (typeof settings.error === "function"){
              settings.error();
          }
          var responseText = "";
          try {
              if (a.responseText){
                  responseText = JSON.parse(a.responseText);
              }
          } catch (e) {
              responseText = "";
          }
          if (a.statusText == 'abort' || b == 'abort '){
              return;
          }
          this.setState({
              uploading: false
          });
          alert($._(responseText.msg) || $._('server error,try again'));
      },
      selectFileComplate: function (e){
          if (this.elements.uploadInput.val()){
              var file = this.elements.uploadInput[0].files[0];

              if (!this.check_accept(file)){
                  alert(file.type + ""+$._('Upload the file in the specified format')+"(" + this.acceptedFiles + ")");
                  return false;
              }

              //
              if (!this.check_size(file)){
                  alert(""+$._('Upload size less than')+"(" + Math.ceil(this.size / 1000000) + "MB)"+$._("dFile")+"");
                  return false;
              }

              this.handleOnSubmit();

              var name = this.filename(file.name) + "(" + this.filesize(file.size) + ')';
              this.setState({
                  uploading: true,
                  fileName: name,
                  status: ''
              });
          } else {
              this.setState({
                  uploading: false,
                  status: ''
              });
          }
      },
      handleOnSubmit: function (e){
          this.elements.uploadForm.ajaxSubmit(this.options);
          return false;
      },
      check_accept: function (file){
          var names = file.name.split('.'),
              accepts = this.accept.split(','), name = names.length > 1 ? names[1] : "";
          if (file.type){
              if (accepts.indexOf(file.type) > -1) return true;
          } else {
              for (var i = 0; i < accepts.length; i++){
                  var accept = accepts[i];
                  if (accept.match(name)){
                     return true;
                  }
              };
          }
          return false;
      },
      check_size: function (file){
          // size为0表示对大小不做限制
          if (this.size !== 0 && file.size > this.size){
              return false;
          }
          return true;
      },
      filename: function (name){
          var filenames = name.split('.'),
              fn = filenames[0],
              fs = '';
          if (filenames.length >= 2){
              fs = filenames[filenames.length - 1];
          }
          if (fn.length > 8){
              fn = fn.substr(0, 8) + '...';
          }
          return fn + "." + fs;
      },
      filesize: function (size){
          var string;
          if (size >= 1024 * 1024 * 1024 * 1024 / 10) {
              size = size / (1024 * 1024 * 1024 * 1024 / 10);
              string = "TB";
          } else if (size >= 1024 * 1024 * 1024 / 10) {
              size = size / (1024 * 1024 * 1024 / 10);
              string = "GB";
          } else if (size >= 1024 * 1024 / 10) {
              size = size / (1024 * 1024 / 10);
              string = "MB";
          } else if (size >= 1024 / 10) {
              size = size / (1024 / 10);
              string = "KB";
          } else {
              size = size * 10;
              string = "b";
          }
          return (Math.round(size) / 10) + string;
      },
      // 重新组装file input，修复选择相同文件之后无法触发onchange的问题
      rebindFileInputEvent: function (){
          var fileStr = '<input ref="uploadInput" name="file" type="file" accept="' + this.accept + '" />';

          this.elements.uploadInput.remove();
          this.elements.uploadInput = $(fileStr).appendTo(this.elements.uploadForm);
          this.elements.uploadInput.bind("change", this.selectFileComplate);
      },
      handleOnStartUpload: function (){
          this.elements.uploadInput.trigger('click');
      },
      handleOnCancelUpload: function (){
          // 取消上传后重新绑定事件，修复选择相同文件无法触发上传事件的问题
          this.rebindFileInputEvent();
          if (this.xhr){
              this.xhr.abort();
          };
          this.setState({
               uploading: false,
               status: ''
          });
      },
      getBuildWidget: function (){
          var type = this.props.type, data;

          data = tool.getWidgetButtonByType(type);
          data = tool.getRebulidWidget(data, this.form.model);
          return data;
      },
      render: function (){
          var replaceNode = "",
              infoInnerNode = "";
          var upload_audio = $._('click to upload audio');
          var replace = $._('Replace');
          var Hint = $._("Hint");
          if (this.state.uploaded){
              replaceNode =
                  <span className="replace_audio">
                      {replace}{this.replaceType}
                  </span>

              infoInnerNode =
                  <div>
                      {this.state.infoHtml}
                  </div>
          } else {
              infoInnerNode =
                  <div>
                      <strong>{Hint}:</strong>
                      <span>{this.upload_info}</span>
                  </div>
          }
          var uploadPercentNode = "";
          if(this.state.uploadPercent == 100){
              uploadPercentNode = <span>文件解析中，请稍候...</span>
          } else {
              uploadPercentNode = 
                  <span>
                      <span>{this.state.fileName}</span>
                      <span>{this.state.uploadPercent + "%"}</span>
                  </span>
          }
          return (
              <div>
                  <div>
                      <div ref="uploadGroup" className={"form-group video_local " + (this.state.uploaded ? "_test" : "")}>
                          <div className="single-upload-group rightVideo">
                              <div className="default-status" style={{visibility:this.state.uploading ? 'hidden' : 'visible'}}>
                                  <span className="input-group-btn">
                                      <button onClick={this.handleOnStartUpload} className="btn btn-default" type="button">
                                          <i className="icon-addfolder">{upload_audio}</i>
                                          {replaceNode}
                                      </button>
                                  </span>
                              </div>
                              <div className="uploading-status" style={{display:this.state.uploading ? 'block' : 'none'}}>
                                  <div className="progress-label">
                                       {uploadPercentNode}
                                  </div>
                                  <div className="progress">
                                      <div className="progress-bar" style={{ width:this.state.uploadPercent +"%"}}></div>
                                  </div>
                                  <span className="btn-close" onClick={this.handleOnCancelUpload}>
                                      <i className="icon-close"></i>
                                  </span>
                              </div>
                             <div className="upload_succ upload_status" style={{display: this.state.status == 'success' ? "block" :'none'}}></div>
                             <div className="upload_error upload_status" style={{display: this.state.status == 'error' ? "block" :'none'}}></div>
                          </div>
                          <form ref="uploadForm" action={this.url} method="POST" encType="multipart/form-data" style={{display:"none"}}>
                              <input ref="uploadInput" onChange={this.selectFileComplate} name="file" type="file" accept={this.accept} />
                              <input name="not_need_narrow" type="hidden" value="true" />
                          </form>
                      </div>
                  </div>
                  <div style={{display:(this.needInfo ? "block" : "none")}} className="info-alert">
                      {infoInnerNode}
                  </div>
              </div>
          )
      }
  });

  module.exports = SingleUpload;
